import 'package:dio/dio.dart';

import '../manager/UserInfoManager.dart';
import '../utils/toast_utils.dart';
import 'Code.dart';
import 'ResultData.dart';

///
/// 拦截器，用于网络数据返回加工预处理
///

class ResponseInterceptors extends Interceptor {
  ///响应前
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    RequestOptions option = response.requestOptions;
    // print("---------response.data----------");
    // print(response.data);
    // print("---------response.data end----------");
    try {
      if (option.contentType != null && option.contentType!.contains("text")) {
        response.data = ResultData(response.data, true, Code.SUCCESS);
        handler.next(response);
        return;
      }

      ///一般只需要处理200的情况，300、400、500保留错误信息，外层为http协议定义的响应码
      if (response.statusCode == 200 || response.statusCode == 201) {
        ///内层需要根据公司实际返回结构解析，一般会有code，data，msg字段
        int status = response.data["status"] ?? response.data["code"];

        // 登录接口  成功200 重新登录401
        // 业务接口  成功0 失败1
        if (status == 200 || status == 0) {
          response.data = ResultData(response.data, true, Code.SUCCESS, headers: response.headers);
          handler.next(response);
          return;
        } else if (status == 401) {
          toast.show('登录过期，请重新登录。', toastLength: Toast.LENGTH_SHORT);
          UserInfoManager().loginOut();
          handler.next(response);
          return;
        } else {
          response.data = ResultData(response.data, false, Code.ERROR, headers: response.headers);
          handler.next(response);
          return;
        }
      } else {
        response.data = ResultData(response.data, false, response.statusCode ?? 404, headers: response.headers);
        handler.next(response);
        return;
      }
    } catch (e) {
      print("ResponseError====$e****${option.path}");
      return;
    }
  }
}
